Skip to main content
Version: 1.0.0

Connect your chart to a UI component

In this tutorial, we will show how you can create a range slider and update the canvas with the filtered data.

Create a UI Component

Let's first create a range slider using html and css.

<div class="slidecontainer">
    <div>Acceleration</div>
      <input type="range" min="1" max="100" value="10" class="slider" id="myRange">
    <div class='rangeval'>
      <span id='val'>0</span>
    </div>
</div>

Here we have created a slider element.

Update canvas data on slider value change

Let's create a function which will filter the DataModel based on the range value in the slider.

const getFilteredData = (dm, value) => {
  return dm.select({
    field: "Horspower",
    value,
    operator: DataModel.ComparisonOperators.LESS_THAN,
  });
};

The above function filters the data with Horsepower value less than the given value.

Now, let's update the data of canvas with the filtered DataModel instance.

slider.oninput = function () {
  document.getElementById("val").innerHTML = this.value;
  const newDm = getFilteredData(dm, value);
  canvas.data().dispose();
  canvas.data(newDm);
};

Note: If a DataModel instance is not being used in the canvas or anywhere, we should dispose the DataModel otherwise it will cause a memory leak.

<div>
  <div class="slidecontainer">
    <div>Horsepower</div>
      <input type="range" min="1" max="100" value="10" class="slider" id="myRange">
    <div class='rangeval'>
      <span id='val'>0</span>
    </div>

</div>
  <div id="chart"></div>
</div>
#chart {
  width: 600px;
  height: 350px;
}

.slidecontainer {
  margin-top: 20px;
  width: 200px;
  font-family: Helvetica;
  margin-bottom: 10px;
}

.slider {
  width: 200px;
}
.slider:hover {
  opacity: 1;
}

.rangeval {
  font-size: 12px;
}
const { muze, getDataFromSearchQuery, env } = viz;
const data = getDataFromSearchQuery();

const domain = data.getField("Horsepower").domain();

const slider = document.getElementById("myRange");
slider.max = domain[1];
slider.min = domain[0] + 5;
slider.value = domain[1];

document.getElementById("val").innerHTML = domain[1];
const filteredDm = dm.select({
  field: "Horsepower",
  value: domain[1],
  operator: DataModel.ComparisonOperators.LESS_THAN,
});

const canvas = muze
  .canvas()
  .data(filteredDm)
  .rows(["Horsepower"])
  .columns(["Cylinders"])
  .mount("#chart");

const getFilteredData = (dm, value) => {
  return dm.select({
    field: "Horsepower",
    value,
    operator: DataModel.ComparisonOperators.LESS_THAN,
  });
};

slider.oninput = function () {
  document.getElementById("val").innerHTML = Math.round(this.value);
  canvas.data(getFilteredData(dm, this.value));
};